package site.luojie.core.parse;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import site.luojie.core.bean.Bean;
import site.luojie.core.bean.BeanProperty;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: beans.xml配置文件解析类
 * @Author jie.luo
 * @Create: 2020-05-01 00:20
 **/
public class XMLBeanParse {

    /**
     * 解析 beans.xml 配置文件
     *
     * @param inputStream 配置文件字节码
     * @return M
     * @throws Exception
     */
    public List<Bean> parse(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();

        List<Bean> beans = new ArrayList<>();
        Bean bean = null;

        // 解析所有的 <bean>
        List<Element> propertyElements = rootElement.selectNodes("//bean");
        for (Element propertyElement : propertyElements) {
            bean = new Bean();
            String id = propertyElement.attributeValue("id");
            String clazz = propertyElement.attributeValue("class");

            bean.setId(id);
            bean.setClassName(clazz);

            BeanProperty beanProperty = null;
            // 解析当前<bean>是否有子节点
            List<Element> properties = propertyElement.selectNodes("//property");
            for (Element property : properties) {
                // <property name="accountDao" ref="accountDao"></property>
                String name = property.attributeValue("name");
                String ref = property.attributeValue("ref");

                // 获取父元素,将property绑定到父元素
                Element parent = property.getParent();
                String parentId = parent.attributeValue("id");
                if (id.equals(parentId)) {
                    beanProperty = new BeanProperty();
                    beanProperty.setName(name);
                    beanProperty.setRef(ref);
                    beanProperty.setParentId(parentId);
                    bean.getBeanProperties().add(beanProperty);
                }
            }

            beans.add(bean);
        }
        return beans;
    }

}
